<?php

namespace App\Http\Logic\Api;

use App\Models\AdminApply;
use App\Models\AdminConfig;
use App\Models\AdminWechatUser;
use Exception;
use Illuminate\Support\Facades\DB;

class ApplyLogic
{
    /**
     * @throws Exception
     */
    public function create($params, $user): array
    {
        try {
            DB::beginTransaction();
            $apply = AdminApply::query()->where('user_id', $user['user_id'])->first();
            if (!empty($apply)) {
                throw new Exception('您已经报名过了');
            }

            AdminWechatUser::query()->where('id', $user['user_id'])->update([
                'nickname' => $params['name'],
                'id_card_number' => $params['id_card_number'],
                'phone' => $params['phone'],
            ]);
            $work_type = AdminConfig::find($params['work_type']);
            $level = AdminConfig::find($params['level']);
            $source =  AdminConfig::find($params['source']);
            return AdminApply::query()->create([
                'user_id' => $user['user_id'],
                'user_name' => $params['name'],
                'id_card_number' => $params['id_card_number'],
                'phone' => $params['phone'],
                'source' => $source['name'] ?? '',
                'work_type' => $work_type['name'] ?? '',
                'level' => $level['name'] ?? '',
                'company' => $params['company'] ?? '',
                'age'=>$params['age'],
                'sex'=>$params['sex'],
                'work_experience' => $params['work_experience'],
                'card_front_image' => $params['card_front_image'],
                'card_back_image' => $params['card_back_image'],
                'head_image' => $params['head_image'] ?? '',
                'diploma_image' => $params['social_security_image'] ?? '',
                'social_security_image' => $params['diploma_image'] ?? '',
                'skill_image' => $params['skill_image'] ?? '',
            ])->toArray();
        } catch (Exception $e) {
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

    public function list($user): array
    {
        return AdminApply::query()->where('user_id', $user['user_id'])->get()->toArray();
    }

    /**
     * @throws Exception
     */
    public function detail($params): array
    {
        $info = AdminApply::query()->find($params['id']);
        if (empty($info)) {
            throw new Exception('数据不存在');
        }

        return $info->toArray();
    }
}
